<template>
  <div class="app-container">
    <!-- 1. 头部区域：手机端简化，PC端保留完整 -->
    <div class="header">
      <!-- 手机端抽屉触发按钮（PC端隐藏） -->
      <el-button
          type="text"
          class="mobile-drawer-btn"
          @click="showMobileSidebar = true"
          v-show="isMobile"
      >
        <el-icon :size="24" color="#2b38ff"><Menu /></el-icon>
      </el-button>

      <!-- Logo + 标题 -->
      <div class="header-logo">
        <img src="@/assets/imgs/logo.png" alt="logo" class="logo-img">
        <span class="header-title" v-show="!isMobile">智慧教育</span>
      </div>

      <!-- 折叠按钮（仅PC端显示） -->
      <div
          class="pc-collapse-btn"
          @click="toggleCollapse"
          v-show="!isMobile"
      >
        <el-icon :size="20" color="#666">
          <Expand v-if="isCollapse"/>
          <Fold v-else/>
        </el-icon>
      </div>

      <!-- 面包屑（PC端完整，手机端简化） -->
      <div class="header-breadcrumb" v-show="!isMobile || router.currentRoute.value.meta.name">
        <span
            class="breadcrumb-home"
            @click="router.push('/manager/home')"
        >
          首页
        </span>
        <span class="breadcrumb-separator" v-if="router.currentRoute.value.meta.name">/</span>
        <span
            class="breadcrumb-current"
            v-if="router.currentRoute.value.meta.name"
        >
          {{ router.currentRoute.value.meta.name }}
        </span>
      </div>

      <!-- 用户信息（手机端简化显示） -->
      <div class="header-user">
        <el-dropdown>
          <div class="user-info-inner">
            <img
                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                alt="user-avatar"
                class="user-avatar"
            >
            <!-- PC端显示完整用户名，手机端显示2字缩写 -->
            <span class="user-name" v-show="!isMobile">
              欢迎您, {{ data.user?.name || '用户' }}
            </span>
            <span class="user-name-mobile" v-show="isMobile">
              {{ data.user?.name?.slice(0, 2) || '用户' }}
            </span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="openPersonDialog" v-if="data.user.username !=='youke'">
                <el-icon><User/></el-icon> 个人信息
              </el-dropdown-item>
              <el-dropdown-item @click="data.passwordDialog=true" v-if="data.user.username !=='youke'">
                <el-icon><Lock/></el-icon> 修改密码
              </el-dropdown-item>
              <el-dropdown-item @click="logout">
                <el-icon><SwitchButton/></el-icon> 退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 2. 主体区域：PC端左右布局，手机端抽屉+单列 -->
    <div class="main-content">
      <!-- 手机端侧边栏抽屉（PC端隐藏） -->
      <el-drawer
          v-model="showMobileSidebar"
          direction="ltr"
          size="75%"
          :with-header="false"
          :modal="true"
          v-show="isMobile"
      >
        <el-menu
            router
            :default-active="router.currentRoute.value.path"
            class="mobile-menu"
            @select="handleMobileMenuSelect"
        >
          <el-menu-item index="/manager/home">
            <el-icon><HomeFilled/></el-icon>
            <template #title>首页</template>
          </el-menu-item>
          <el-menu-item index="/manager/admin" v-if="data.user.role==='ADMIN'">
            <el-icon><UserFilled/></el-icon>
            <template #title>用户管理</template>
          </el-menu-item>
          <el-menu-item index="/manager/student" v-if="data.user.role==='ADMIN'">
            <el-icon><User/></el-icon>
            <template #title>学生管理</template>
          </el-menu-item>
          <el-menu-item index="/manager/exam">
            <el-icon><Document/></el-icon>
            <template #title>考试信息</template>
          </el-menu-item>
          <el-menu-item index="/manager/scores">
            <el-icon><Histogram/></el-icon>
            <template #title>成绩分析</template>
          </el-menu-item>
          <el-menu-item index="/manager/fenxi">
            <el-icon><EditPen/></el-icon>
            <template #title>积分计算</template>
          </el-menu-item>
          <el-menu-item index="/manager/seat">
            <el-icon><Setting /></el-icon>
          <template #title>座位工具</template>
        </el-menu-item>
        </el-menu>
      </el-drawer>

      <!-- PC端侧边栏（手机端隐藏） -->
      <div
          class="pc-sidebar"
          :class="isCollapse ? 'sidebar-collapsed' : 'sidebar-expanded'"
          v-show="!isMobile"
      >
        <el-menu
            router
            :default-active="router.currentRoute.value.path"
            :collapse="isCollapse"
            :collapse-transition="true"
            class="pc-menu"
            style="min-height: calc(100vh - 60px)"
        >
          <el-menu-item index="/manager/home">
            <el-icon><HomeFilled/></el-icon>
            <template #title>首页</template>
          </el-menu-item>
          <el-menu-item index="/manager/admin" v-if="data.user.role==='ADMIN'">
            <el-icon><UserFilled/></el-icon>
            <template #title>用户管理</template>
          </el-menu-item>
          <el-menu-item index="/manager/student" v-if="data.user.role==='ADMIN'">
            <el-icon><User/></el-icon>
            <template #title>学生管理</template>
          </el-menu-item>
          <el-menu-item index="/manager/exam">
            <el-icon><Document/></el-icon>
            <template #title>考试信息</template>
          </el-menu-item>
          <el-menu-item index="/manager/scores">
            <el-icon><Histogram/></el-icon>
            <template #title>成绩分析</template>
          </el-menu-item>
          <el-menu-item index="/manager/fenxi">
            <el-icon><EditPen/></el-icon>
            <template #title>积分计算</template>
          </el-menu-item>
          <el-menu-item index="/manager/seat">
            <el-icon><Setting /></el-icon>
            <template #title>座位工具</template>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区（适配所有屏幕） -->
      <div class="content-wrapper">
        <RouterView />
      </div>
    </div>

    <!-- 3. 个人信息对话框（手机端自适应宽度） -->
    <el-dialog
        v-model="data.personDialog"
        title="个人信息"
        :width="isMobile ? '85%' : '500px'"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :rules="data.rules"
          :model="data.form"
          label-width="80px"
          status-icon
          class="dialog-form"
      >
        <el-form-item prop="username" label="账号">
          <el-input v-model="data.form.username" autocomplete="off" :disabled="!!data.form.id"/>
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model="data.form.name" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.personDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePerson">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 4. 修改密码对话框（手机端自适应宽度） -->
    <el-dialog
        v-model="data.passwordDialog"
        title="修改密码"
        :width="isMobile ? '85%' : '500px'"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :rules="data.rules"
          :model="data.form"
          label-width="80px"
          status-icon
          class="dialog-form"
      >
        <el-form-item prop="username" label="账号">
          <el-input v-model="data.user.username" autocomplete="off" :disabled="!!data.form.id"/>
        </el-form-item>
        <el-form-item prop="password" label="原密码">
          <el-input show-password v-model="data.form.password" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input show-password v-model="data.form.newPassword" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input show-password v-model="data.form.confirmPassword" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.passwordDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import router from "@/router/index.js";
import { reactive, ref, onMounted, watch } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElDrawer } from "element-plus";
// 引入所需图标
import {
  HomeFilled, UserFilled, User, Document, Histogram, EditPen,
  Expand, Fold, Menu, Lock, SwitchButton
} from "@element-plus/icons-vue";

// 密码一致性校验
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== data.form.newPassword) {
    callback(new Error("两次输入的新密码不一致！"))
  } else {
    callback()
  }
}

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  passwordDialog: false,
  personDialog: false,
  form: { id: '' }, // 初始化表单ID，避免undefined警告
  rules: {
    password: [
      { required: true, message: '请填写原密码', trigger: 'blur' },
      { min: 3, message: '密码最少3位', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请填写名称', trigger: 'blur' },
      { min: 1, message: '名称最少1位', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '请填写新密码', trigger: 'blur' },
      { min: 3, message: '密码最少3位', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      { validator: validatePass, trigger: 'blur' }
    ],
  }
})

// 1. 响应式判断：是否为手机端（768px以下）
const isMobile = ref(false)
// 2. PC端侧边栏折叠状态
const isCollapse = ref(false)
// 3. 手机端侧边栏抽屉显示状态
const showMobileSidebar = ref(false)
// 4. 表单ref
const formRef = ref()

// 检查设备类型（初始化 + 窗口 resize 时更新）
const checkDeviceType = () => {
  isMobile.value = window.innerWidth < 768
  // 手机端强制展开PC侧边栏（避免折叠状态混乱）
  if (isMobile.value) isCollapse.value = false
}

// 初始化
onMounted(() => {
  checkDeviceType()
  window.addEventListener('resize', checkDeviceType)
  // 初始化表单ID
  data.form.id = data.user.id || ''
  // 未登录跳转（注释解除后生效）
  // if (!data.user?.id) {
  //   router.push('/login')
  //   ElMessage.error('请登录您的账号')
  // }
})

// 清理窗口监听（避免内存泄漏）
watch(router.currentRoute, (newVal) => {
  if (newVal.path === '/login') {
    window.removeEventListener('resize', checkDeviceType)
  }
})

// PC端侧边栏折叠切换
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 手机端菜单选择后关闭抽屉
const handleMobileMenuSelect = () => {
  showMobileSidebar.value = false
}

// 修改密码
const updatePassword = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/updatePassword', data.form).then(res => {
        if (res.code === '200') {
          ElMessage.success('修改成功')
          data.passwordDialog = false
          localStorage.removeItem('code_user')
          router.push('/login')
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

// 打开个人信息对话框
const openPersonDialog = () => {
  data.form.username = data.user.username || ''
  data.form.name = data.user.name || ''
  data.personDialog = true
}

// 更新个人信息
const updatePerson = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/updatePerson', data.form).then(res => {
        if (res.code === '200') {
          data.user = res.data;
          localStorage.setItem('code_user', JSON.stringify(data.user));
          ElMessage.success('修改成功')
          data.personDialog = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

// 退出登录
const logout = () => {
  localStorage.removeItem('code_user')
  ElMessage.success('已成功退出！')
  router.push('/login')
  showMobileSidebar.value = false // 退出时关闭手机端抽屉
}

if (!data.user?.id) {
  router.push('/login')
  ElMessage.error('请登录您的账号')
}
</script>

<style scoped>
/* 全局容器：占满屏幕高度 */
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

/* 1. 头部样式 */
.header {
  height: 60px;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 12px;
  background: #fff;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
  z-index: 10;
}

/* 手机端抽屉按钮 */
.mobile-drawer-btn {
  padding: 6px;
  margin-right: 8px;
}

/* Logo + 标题 */
.header-logo {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 16px;
}

.logo-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  color: #2b38ff;
}

/* PC端折叠按钮 */
.pc-collapse-btn {
  padding: 0 15px;
  cursor: pointer;
  margin-right: 12px;
}

/* 面包屑 */
.header-breadcrumb {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.breadcrumb-home {
  cursor: pointer;
  color: #2b38ff;
}

.breadcrumb-separator {
  margin: 0 6px;
  color: #ccc;
}

.breadcrumb-current {
  color: #333;
  font-weight: 500;
}

/* 用户信息 */
.header-user {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.user-info-inner {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.user-info-inner:hover {
  background-color: #f0f4ff;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.user-name {
  font-size: 14px;
  color: #333;
}

/* 手机端用户名简化（2字缩写+圆形背景） */
.user-name-mobile {
  font-size: 14px;
  color: #333;
  background: #f0f4ff;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 2. 主体内容区 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 手机端侧边栏抽屉菜单 */
.mobile-menu {
  height: 100%;
  border-right: none;
  padding-top: 20px;
  background-color: #fff;
}

.mobile-menu .el-menu-item {
  height: 48px; /* 增大点击区域，适配触屏 */
  margin: 4px 12px;
  border-radius: 6px;
  font-size: 15px;
}

.mobile-menu .el-menu-item:hover {
  background-color: #f0f4ff;
  color: #2b38ff;
}

/* PC端侧边栏 */
.pc-sidebar {
  transition: width 0.3s ease-in-out;
  background: #fff;
  box-shadow: 2px 0 8px rgba(29,35,41,0.05);
}

/* PC端侧边栏展开状态 */
.sidebar-expanded {
  width: 180px;
}

/* PC端侧边栏折叠状态 */
.sidebar-collapsed {
  width: 64px;
}

/* PC端菜单 */
.pc-menu {
  border-right: none;
  transition: all 0.3s;
}

.pc-menu .el-menu-item {
  transition: all 0.2s;
  margin: 4px 8px;
  border-radius: 4px;
}

.pc-menu .el-menu-item:hover {
  background-color: #f0f4ff;
  color: #2b38ff;
}

.pc-menu.el-menu--collapse .el-menu-item {
  display: flex;
  justify-content: center;
  padding: 0 !important;
  margin: 8px 0;
  height: 40px;
}

/* 主内容区 */
.content-wrapper {
  flex: 1;
  padding: 16px;
  background-color: aliceblue;
  overflow-y: auto;
  box-sizing: border-box;
}

/* 3. 对话框样式 */
.dialog-form {
  padding: 12px 0;
  margin: 0;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 4. 响应式断点（768px以下为手机端） */
@media (max-width: 768px) {
  /* 头部：降低高度，简化布局 */
  .header {
    height: 56px;
    padding: 0 8px;
  }

  /* 隐藏PC端专属元素 */
  .pc-collapse-btn,
  .header-title {
    display: none;
  }

  /* 面包屑：简化间距，避免溢出 */
  .header-breadcrumb {
    margin: 0 8px;
    font-size: 13px;
  }

  /* 主内容区：减小padding，避免贴边 */
  .content-wrapper {
    padding: 10px 8px;
  }

  /* 对话框按钮：适配手机触屏 */
  .dialog-footer .el-button {
    padding: 8px 16px;
    font-size: 14px;
  }
}

/* 小屏手机适配（480px以下） */
@media (max-width: 480px) {
  .user-avatar {
    width: 36px;
    height: 36px;
  }

  .mobile-menu .el-menu-item {
    height: 44px;
    font-size: 14px;
  }

  .dialog-form .el-form-item {
    margin-bottom: 12px;
  }

  .dialog-form .el-input {
    font-size: 14px;
  }
}
</style>